<!-- from approval.vue -->
<template>
  <base-breadcrumb>
    <h2>审批</h2>
    <a-card :body-style="{ padding: '24px 32px' }" :bordered="false">
      <title-name title="节点信息" />
      <slot name="extraResult" />
      <a-descriptions class="mb20" title="">
        <a-descriptions-item label="当前节点">
          {{ taskName }}
        </a-descriptions-item>
        <a-descriptions-item label="审批人">
          {{ currentUser.name }}
        </a-descriptions-item>
        <a-descriptions-item label="审批时间">
          {{ currentTime }}
        </a-descriptions-item>
      </a-descriptions>
      <!-- 审批意见 -->
      <titleName title="审批意见"></titleName>
      <a-form-model ref="reviewFormRef" :model="reviewOptions.form" :rules="reviewOptions.rules" :labelCol="{ lg: { span: 6 }, sm: { span: 6 } }" :wrapperCol="{ lg: { span: 16 }, sm: { span: 16 } }">
        <a-row :gutter="24">
          <a-col v-for="(item, idx) in reviewOptions.keyMap[taskDefKey]" :key="idx">
            <a-form-model-item :label="item.label" :prop="item.key">
              <BaseTextarea placeholder="请输入" v-model="reviewOptions.form[item.key]" />
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
      <!-- 意见征询（通用） -->
      <Consultation :proc-inst-id="procInstId" :is-show-btn="$route.query.isMonitoring ? ($route.query.monitoringType === 'process' ? true : false) : true" :task-name="taskName" :sub-approver-list.sync="subApproverList">
        <template slot="approverButton">
          <a-button type="primary" :loading="loading.REJECT" @click="handleSave('REJECT')">审批不通过</a-button>
          <a-button type="primary" :loading="loading.PASS" @click="handleSave('PASS')">审批通过</a-button>
        </template>
      </Consultation>
      <title-name title="审批流程信息" />
      <div class="btns-wrapp mb20">
        <a-button type="primary" @click="visibleState.auditProcess = true"> 审批流程图 </a-button>
      </div>
      <a-spin tip="流程信息加载中..." :spinning="flowRequesting" />
      <a-table :columns="columnApprove" :data-source="approveInfos" bordered>
        <span slot="serial" slot-scope="text, record, index">{{ index + 1 }}</span>
        <template slot="opinions" slot-scope="text, record">
          <a-tooltip placement="topLeft">
            <template slot="title">
              <span> {{ record.formData.opinions }}</span>
            </template>
            <span> {{ record.formData.opinions }}</span>
          </a-tooltip>
        </template>
      </a-table>
    </a-card>
    <!-- 分包商进场申请详情 -->
    <h2>分包商进场申请详情</h2>
    <Details></Details>
    <ApprovalDetails :title="'审批流程信息'" :business-id="id" :visible="visibleState.auditProcess" @cancel="visibleState.auditProcess = false" @confirm="visibleState.auditProcess = false" />
  </base-breadcrumb>
</template>
<script>
import ApprovalDetails from '@/components/approvalDetails'
import { addPersonalFinanceAudit, addPersonalCommercialAudit, checkPersonalRiskReturn } from '@/api/businessAffairs/riskRefund'
import { getOrganizePeopleList } from '@/api/safetySupervision/emergencyDrill'
import { getOrgEmployeesListBy } from '@/api/commons'
import { getProcessNodeList, completeTask } from '@/api/process'
import { getSelectListByType } from '@/api/businessAffairs/common.js'
import SelectSubCompany from '@/components/Select/SelectSubCompany' // 分公司
import SelectProject from '@/components/Select/SelectProject' // 分公司
import Consultation from '@/views/matters/approval/components/consultation'
import { isAttachment } from '@/utils/util'
import Vue from 'vue'
import moment from 'moment'
import UploadList from '@/components/UploadList'
import Details from './details.vue'

const columnApprove = [
  {
    title: '序号',
    width: 80,
    align: 'center',
    scopedSlots: { customRender: 'serial' }
  },
  {
    title: '审批人',
    dataIndex: 'userName',
    ellipsis: true,
    width: 180
  },
  {
    title: '审批时间',
    dataIndex: 'endTime',
    ellipsis: true,
    width: 180
  },
  {
    title: '节点名称',
    dataIndex: 'taskName',
    ellipsis: true,
    width: 180
  },
  {
    title: '滞留时间',
    dataIndex: 'durationInMillis',
    ellipsis: true,
    width: 140
  },
  {
    title: '审批意见',
    dataIndex: 'formData.opinions',
    scopedSlots: { customRender: 'opinions' },
    ellipsis: true
  }
]
export default {
  name: 'a' + Date.now(),
  components: {
    SelectSubCompany,
    SelectProject,
    UploadList,
    Details,
    ApprovalDetails,
    Consultation
  },
  data() {
    const validator = (rule, value, callback) => {
      console.log(value)
      if (!value[0]) {
        callback(new Error('请输入风险金百分比！'))
      } else if (!value[1]) {
        callback(new Error('请输入风险金额度！'))
      } else {
        callback()
      }
    }
    return {
      visibleState: {
        auditProcess: false
      },
      loading: {
        PASS: false,
        REJECT: false
      },
      form: { financeAuditVO: {}, commercialAuditVO: {} },
      rules1: {
        creditReturnAmount: [{ required: true, message: '请输入' }],
        financeOpinions: [{ required: true, message: '请输入' }]
      },
      rules2: {
        returnAmount: [{ required: true, message: '请输入' }],

        commercialOpinions: [{ required: true, message: '请输入' }]
      },
      fetchingOrganizePeopleList: false,
      organizePeopleList: [],
      id: '',
      isSubmit: true,
      pageType: '',
      approveInfos: [], // 审批流程信息
      procInstId: '', //当前流程实例ID
      taskId: '', //当前流程节点ID
      processName: '', //流程名称
      taskName: '', //当前流程节点名称
      taskDefKey: '', //任务标识
      currentTime: '', //当前审批时间
      currentUser: '', //当前审批人
      flowRequesting: false,
      detailUrl: null, //详情地址

      assignType: '', //节点类型   0 变量获取 1 处理人 2 候选人 3 候选组 4 会签
      assignCode: '', //候选组编码 岗位编码
      assignLevel: '', //层级 项目部 PD 分公司 BC 公司 CO
      businessType: '', //业务类型 0 项目
      // 下级审批人
      subApproverList: [],
      // 流程表头
      columnApprove,
      // 审批意见相关
      reviewOptions: {
        keyMap: {
          // 项目部_商务主管/商务工程师_审批
          XMB_SWZG_SWGCS_AUDIT: [{ label: '合同签订情况：', key: 'field1' }],
          // 项目部_财务主管_审批
          XMB_CWZG_AUDIT: [{ label: '分包履约保证金是否足额缴纳：', key: 'field1' }],
          // 项目部_专业工程师/专业主管_审批
          XMB_ZYGCS_ZYZG_AUDIT: [
            { label: '分包施工方案及施工进度计划：', key: 'field1' },
            { label: '临时设施需用计划：', key: 'field2' }
          ],
          // 项目部_劳务工程师/劳务主管_审批
          XMB_LWGCS_LWZG_AUDIT: [
            { label: '分包资源现场人员花名册及其附件：', key: 'field1' },
            { label: '工人工资保证金单据：', key: 'field2' }
          ],
          // 项目部_材料工程师/材料主管_审批
          XMB_CLGCS_CLZG_AUDIT: [{ label: '物资机具清单：', key: 'field1' }],
          // 项目部_项目经理_审批
          XMB_XMJL_AUDIT: [{ label: '项目经理部意见：', key: 'field1' }]
        },
        form: {
          field1: '',
          field2: ''
        },
        rules: {
          field1: [{ required: true, message: '请输入' }],
          field2: [{ required: true, message: '请输入' }]
        }
      }
    }
  },
  created() {
    this.init()
  },
  methods: {
    init() {
      this.$checkRequireItem()
      this.form.user = JSON.parse(sessionStorage.getItem('ycloud-user_info')).username
      this.id = this.$route.query.id
      const { type, code, level, btype, businessId, procInstId, name, processName, detailUrl, taskId, taskDefKey } = this.$route.query
      if (type) {
        this.assignType = type
        this.assignCode = code
        this.assignLevel = level
        this.businessType = btype
      }
      this.id = businessId
      // this.taskDefKey = 'GS_CWZJBJL_AUDIT'
      if (!this.id) {
        this.$error({ content: '无指定业务ID，将自动关闭' })
        setTimeout(() => {
          window.close()
        }, 1500)
        return
      }
      this.procInstId = procInstId
      this.currentUser = Vue.getAcloudProvider().getUserInfo()
      this.taskName = decodeURIComponent(name)
      this.processName = decodeURIComponent(processName)
      document.title = this.processName + '-' + this.taskName
      if (detailUrl) {
        this.detailUrl = decodeURIComponent(detailUrl)
      }
      this.taskId = taskId
      this.taskDefKey = taskDefKey

      this.currentTime = moment().format('yyyy-MM-DD HH:mm')
      // this.checkPersonalRiskReturnReq()
      //获取流程节点执行情况
      this.getProcessNodes()
    },
    //获取项目下的人员列表
    getOrganizePeopleList() {
      let params = {
        id: this.form.projectId
      }
      this.organizePeopleList = []
      this.fetchingOrganizePeopleList = true
      getOrganizePeopleList(params).then(res => {
        this.fetchingOrganizePeopleList = false
        let obj = {}
        res.data = res.data.reduce((cur, next) => {
          obj[next.employeeId] ? '' : (obj[next.employeeId] = true && cur.push(next))
          return cur
        }, []) //设置cur默认类型为数组，并且初始值为空的数组
        console.log(res.data)
        this.organizePeopleList = res.data || []
      })

      console.log(this.organizePeopleList)
    },
    async checkPersonalRiskReturnReq() {
      const [err, res] = await checkPersonalRiskReturn({ id: this.id })
      if (!err) {
        res.data.commercialAuditVO = res.data.commercialAuditVO || {}
        res.data.financeAuditVO = res.data.financeAuditVO || {}
        this.form = res.data
        this.getOrganizePeopleList()
      }
    },
    // 处理增、删、改操作
    async handleSave(status) {
      if (this.loading[status]) return

      this.$refs['reviewFormRef'].validate(valid => {
        if (!valid) return

        if (status === 'PASS') {
          this.handelApproval()
          return
        }

        if (status === 'REJECT') {
          this.handelUnApproval()
        }
      })
    },

    // 审批不通过
    handelUnApproval(staus) {
      const _this = this
      const confirmWin = this.$confirm({
        title: '警告提醒！',
        content: '确定审批不通过？',
        okType: 'danger',
        onOk() {
          return new Promise((resolve, reject) => {
            _this
              .submit(true, staus)
              .then(() => {
                resolve()
                confirmWin.destroy()
              })
              .catch(() => reject)
          }).catch(() => this.$error({ content: '审批提交失败，请稍后重试' }))
        },
        onCancel() {}
      })
    },

    // 审批通过
    handelApproval() {
      const _this = this
      const confirmWin = this.$confirm({
        title: '警告提醒！',
        content: '确定审批通过？',
        okType: 'danger',
        onOk() {
          return new Promise((resolve, reject) => {
            _this
              .submit(false, _this.createApproverList(_this.subApproverList))
              .then(() => {
                resolve()
                confirmWin.destroy()
              })
              .catch(() => reject)
          }).catch(() => this.$error({ content: '审批提交失败，请稍后重试' }))
        },
        onCancel() {}
      })
    },
    notifyParent() {
      window.opener.postMessage('finish', window.location.origin)
    },
    /**
     * @description: 组装下级审批人数据
     * @param {array} subApproverList 下级审批人表格数据
     * @return {object} 下级审批人数据
     */
    createApproverList(subApproverList) {
      const subordinateApproverList = {}
      subApproverList.forEach(item => {
        if (item?.approver && item.approver.length > 0) {
          subordinateApproverList[item.taskInfo.id] = {
            assgins: item.approver?.map(el => el.key).join(','),
            assignTypeEnum: 2
          }
        }
      })
      return subordinateApproverList
    },
    async submit(reject) {
      let opinions = this.reviewOptions.keyMap[this.taskDefKey].map(item => item.label + this.reviewOptions.form[item.key])
      let str = ''
      switch (opinions.length) {
        case 1:
          str = opinions[0]
          break
        case 2:
          opinions = opinions.map((item, idx) => `${idx + 1}.${item}`)
          str = opinions.join('\n')
          break

        default:
          break
      }

      const data = {
        formData: {
          opinions: str,
          reject
        },
        procInstId: this.procInstId,
        taskId: this.taskId,
        userId: this.currentUser.id
      }
      if (reject) {
        data['variables'] = { reject: true }
      }
      return completeTask(data)
        .then(res => {
          if (res.status === 200) {
            this.notifyParent() // 通知父窗口
            // this.$success({
            //   content: '审批提交成功，即将自动关闭当前窗口',
            //   onOk() {
                window.close()
            //   }
            // })
            // setTimeout(() => {
            //   window.close()
            // }, 2000)
          } else {
            this.$error({ content: '审批提交失败，请稍后重试' })
          }
          return res
        })
        .catch(err => {
          return err
        })
    },
    /**
     * @description: 获取流程信息
     * @return {void}
     */

    getProcessNodes() {
      this.flowRequesting = true
      getProcessNodeList({ procInstId: this.procInstId, pageNo: 1, pageSize: 100 })
        .then(res => {
          if (res.code === 200) {
            const data = res.data
            const userIds = data.map(d => {
              if (d.formData) {
                d.formData = JSON.parse(d.formData)
              }
              return d.assignee
            })
            getOrgEmployeesListBy({ userIds, delete: true }).then(employees => {
              this.flowRequesting = false
              res.data.forEach(r => {
                employees.data.some(e => {
                  if (e.userId === r.assignee) {
                    r.userName = e.name
                    return true
                  }
                })
              })
              this.approveInfos = res.data.map((el, index) => {
                el.key = index
                return el
              })
              console.log(res.data)
            })
          }
        })
        .catch(() => {
          this.flowRequesting = false
        })
    }
  }
}
</script>
<style lang="less" scoped>
@deep: ~'>>>';
.tool-btns {
  display: flex;
  justify-content: flex-end;
  @{deep} .ant-btn + .ant-btn {
    margin-left: 12px;
  }
}
.tx {
  color: rgba(0, 0, 0, 0.85);
  font-size: 14px;
  margin-left: 30px;
}
.return-ratio .ant-form-item-children .ant-form-explain {
  margin-left: 230px;
}
.item {
  margin-left: 60px;
}
.item .ant-form-item {
  margin-top: -28px;
}
</style>
